package cn.fuxi2022.accounts.reply.controller;


import cn.fuxi2022.accounts.reply.service.AccountsReplyService;
import cn.fuxi2022.core.exception.SmartGroupException;
import cn.fuxi2022.model.empty.accounts.AccountsReply;
import cn.fuxi2022.model.resp.PageUtils;
import cn.fuxi2022.model.resp.R;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Map;

/**
 * <p>
 * 微信消息回复表 前端控制器
 * </p>
 *
 * @author Fuxi
 * @since 2022-10-18 08:27:33
 */
@RestController
@RequestMapping("/admin/reply")
public class AccountsReplyController {

    @Autowired
    private AccountsReplyService accountsReplyService;

    @GetMapping("/selectTypeList")
    public R getSelectList() {
        LambdaQueryWrapper<AccountsReply> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(AccountsReply::getName).orderByDesc(AccountsReply::getGmtModified);
        return R.ok().data(accountsReplyService.list(wrapper));
    }

    /**
     * 列表
     */
    @PostMapping("/list")
    public R list(@RequestBody Map<String, Object> params) {
        PageUtils page = accountsReplyService.queryPage(params);

        return R.ok().data(page);
    }

    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") String id) {
        AccountsReply accountsReply = accountsReplyService.getById(id);

        return R.ok().data("accountsReply", accountsReply);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    public R save(@RequestBody @Validated(AccountsReply.Save.class) AccountsReply accountsReply) {

        // 判断关键字是否重复
        LambdaQueryWrapper<AccountsReply> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AccountsReply::getName, accountsReply.getName());
        long count = accountsReplyService.count(wrapper);
        if (count > 0) {
            throw new SmartGroupException("关键字重复，无法录入");
        }
        accountsReplyService.save(accountsReply);

        return R.ok("保存成功");
    }

    /**
     * 修改
     */
    @PutMapping("/update")
    public R update(@RequestBody @Validated(AccountsReply.Update.class) AccountsReply accountsReply) {
        accountsReplyService.updateById(accountsReply);

        return R.ok("修改回复成功");
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete")
    public R delete(@RequestBody String[] ids) {
        if (Arrays.asList(ids).contains("1")) {
            throw new SmartGroupException("关注后回复消息不可删除");
        } else if (Arrays.asList(ids).contains("0")) {
            throw new SmartGroupException("关键词不匹配的回复消息不可删除");
        }

        accountsReplyService.removeByIds(Arrays.asList(ids));

        return R.ok("删除回复成功");
    }
}
